﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Domain.Wrappers;
using Cms.Web.Framework.Controls;
using Cms.Web.Framework.Plugins.Attributes;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using iLib.Web.UI.WebControls;

namespace Cms.Web.UI.Admin.tiny_mce.plugins.frediumplugins
{
    public partial class frediumplugins : AdminPopupBasePage, IFrediumPluginsPopupView
    {
        private FrediumPluginsPopupPresenter _presenter;

        #region IFrediumPluginsPopupView Members

        public void SetPlugins(IList<PluginDescription> plugins)
        {
            ddlPlugins.Items.Clear();
            foreach (PluginDescription pd in plugins)
            {
                ddlPlugins.Items.Add(new ListItem(pd.Name, pd.Plugin.ID.ToString()));
            }
            ddlPlugins.Items.Insert(0, new ListItem(Translator.GetText(ContextTranslationFile, "ddlPluginsDefaultValue", Localization), "-1"));
        }


        public int SelectedPluginID
        {
            get { return int.Parse(ddlPlugins.SelectedValue); }
        }


        public void SetPluginInfo(string description, string className, string assemblyName)
        {
            litDescription.Text = description;
            hidClassName.Value = className;
            hidAssemblyName.Value = assemblyName;
        }


        public void SetTemplates(IList<PluginTemplate> templates, bool templatablePlugin)
        {
            ddlTemplates.Items.Clear();
            string selectedTemplateId = GetPropertyValue("templateid");
            foreach (PluginTemplate t in templates)
            {
                ListItem li = new ListItem(t.Name, t.ID.ToString());
                if (t.ID.ToString() == selectedTemplateId)
                {
                    li.Selected = true;
                }
                ddlTemplates.Items.Add(li);
            }
            ddlTemplates.Visible = templates.Count > 0;
            tdSelectTemplate.Visible = ddlTemplates.Visible;
            pnlNoTemplates.Visible = templates.Count == 0 && templatablePlugin;
            hidTemplatablePlugin.Value = templatablePlugin ? "true" : "false";
        }


        public void SetProperties(IList<PluginPropertyDescription> properties)
        {
            rpProperties.DataSource = properties;
            rpProperties.DataBind();
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/FrediumPlugins.xml"; }
        }


        public string Localization
        {
            get
            {
                HttpCookie cookie = Request.Cookies["FrediumAdminLocalization"];
                if (cookie != null)
                    return cookie.Value;
                else
                    return "en-US";
            }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            baseTag.Attributes.Add("href", Url.FullPath);
            Page.Header.Controls.Add(new iLibRegistrator());
            ddlPlugins.Attributes.Add("onchange", "triggerUpdate();");
            _presenter = new FrediumPluginsPopupPresenter(this);
            if (!Page.IsPostBack)
            {
                _presenter.Initialize();
                Header.Title = Translator.GetText(ContextTranslationFile, "Heading", Localization);
                form1.Action = Url.FoldersAndPage + Url.Querystring;
                ddlTemplates.Visible = false;
                tdSelectTemplate.Visible = false;
            }
            else
            {
                if (ViewState["ButtonsIsSet"] == null)
                {
                    llInsert.Visible = hidPropertyList.Value == "";
                    llUpdate.Visible = !llInsert.Visible;
                    ViewState["ButtonsIsSet"] = true;
                    upnlButtons.Update();
                }
            }
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (ddlPlugins.SelectedValue != "-1" && ddlPlugins.Items[0].Value == "-1")
                ddlPlugins.Items.RemoveAt(0);
            upnlPlugins.Update();
        }


        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (SelectedPluginID > 0)
            {
                pnlPlugin.Visible = true;
                _presenter.GetPlugin();
            }
            else
                pnlPlugin.Visible = false;
        }


        protected void rpProperties_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var property = (e.Item.DataItem as PluginPropertyDescription);
            var litName = (Literal) e.Item.FindControl("litName");
            var txtValue = (TextBox) e.Item.FindControl("txtValue");
            var litBrowse = (Literal) e.Item.FindControl("litBrowse");
            var ddlValues = (iDropDownList) e.Item.FindControl("ddlValues");
            var chkValue = (CheckBox) e.Item.FindControl("chkValue");
            litName.Text = Translator.GetText("Admin/Translations/Plugins/" + property.ClassName + ".xml", property.Name,
                                              Localization);
            // Find enumeration attibute
            bool mandatoryEnumeration = false;
            foreach (object attribute in property.Info.GetCustomAttributes(typeof (EnumerationAttribute), true))
            {
                property.Enumeration = (attribute as EnumerationAttribute).Enumeration;
                mandatoryEnumeration = (attribute as EnumerationAttribute).Mandatory;
                break;
            }
            if (property.Enumeration != null)
            {
                ddlValues.Visible = true;
                ddlValues.Attributes.Add("property", property.Name);
                if (property.Enumeration == "Categories")
                {
                    CategoriesDropDownHelper.SetCategoryTree(ref ddlValues, 0, _presenter.GetRootCategories());
                }
                else
                {
                    foreach (var item in _presenter.GetEnumerationTypeItems(property.Enumeration, property.ClassName))
                    {
                        ddlValues.Items.Add(new ListItem(item.Value, item.Key));
                    }
                }
                ddlValues.SelectedValue = GetPropertyValue(property.Name);
                if (!mandatoryEnumeration)
                    ddlValues.Items.Insert(0,
                                           new ListItem(
                                               Translator.GetText(
                                                   "Admin/Translations/Plugins/" + property.ClassName + ".xml",
                                                   "NonMandatoryDropDownListDefault", Localization)
                                               , "-1"));
                return;
            }
            if (property.Info.PropertyType == typeof (bool))
            {
                chkValue.Visible = true;
                chkValue.Attributes.Add("property", property.Name);
                chkValue.Checked = GetPropertyValue(property.Name).ToLower() == "true";
                return;
            }
            txtValue.Visible = true;
            txtValue.Attributes.Add("property", property.Name);
            txtValue.Text = GetPropertyValue(property.Name);
            // Find browse attibute
            string mode =
                property.Info.GetCustomAttributes(typeof (BrowseAttribute), true).Select(
                    attribute => (attribute as BrowseAttribute).Mode).FirstOrDefault();
            if (mode != null)
            {
                litBrowse.Text = "<a id=\"" + txtValue.ClientID + "_link\" " +
                                 "href=\"javascript:openBrowser('" + txtValue.ClientID + "_container', '" +
                                 txtValue.ClientID +
                                 "', '" + mode + "', 'frediumplugins_" + mode +
                                 "_browser_callback');\" " +
                                 "onmousedown=\"return false;\" " +
                                 "class=\"browse\"><span id=\"" + txtValue.ClientID +
                                 "_container\" title=\"Browse\">&nbsp;</span></a>";
            }
            int height =
                property.Info.GetCustomAttributes(typeof (MultiRowAttribute), true).Select(
                    attribute => (attribute as MultiRowAttribute).Height).FirstOrDefault();
            if (height > 0)
                txtValue.Height = height;
            if (property.Info.GetCustomAttributes(typeof (CodeAttribute), true).Any())
            {
                txtValue.CssClass = "code";
                txtValue.Width = 400;
                txtValue.TextMode = TextBoxMode.MultiLine;
            }
        }


        private string GetPropertyValue(string propertyName)
        {
            string pl = hidPropertyList.Value;
            if (pl.Trim() == "")
                return "";
            foreach (string kvp in pl.Split(",".ToCharArray()))
            {
                string key = kvp.Substring(0, kvp.IndexOf(":"));
                if (key.ToLower() == propertyName.ToLower())
                {
                    string value = kvp.Substring(kvp.IndexOf(":") + 2)
                        .TrimEnd("'".ToCharArray())
                        .Replace("%22", "\"")
                        .Replace("%3c", "<")
                        .Replace("%3e", ">")
                        .Replace("%27", "'")
                        .Replace("%5c", "\\")
                        .Replace("%25", "%");
                    return value;
                }
            }
            return "";
        }
    }
}